﻿/*******************************************************
* 
* 创建人：秦波
* 创建日期：2014年1月13日17:23:48
* 创建说明：Json转换类
* 修改人：
* 修改日期：
* 修改说明：
*
*******************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace Matrix.Common.Utility
{
    public class JsonLib
    {
        #region Json和对象的转换

        /// <summary>
        /// 将对象转换为Json
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ObjToJson(object value)
        {
            Type type = value.GetType();
            var json = new Newtonsoft.Json.JsonSerializer
            {
                NullValueHandling = NullValueHandling.Ignore,
                ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace,
                MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            var sw = new System.IO.StringWriter();
            var writer = new JsonTextWriter(sw) {Formatting = Formatting.None, QuoteChar = '"'};
            json.Serialize(writer, value);
            string output = sw.ToString();
            writer.Close();
            sw.Close();
            return output;
        }

        /// <summary>
        /// 将Json字符串转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonText"></param>
        /// <returns></returns>
        public static T JsonToObj<T>(string jsonText)
        {
            var json = new Newtonsoft.Json.JsonSerializer
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace,
                MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            };
            var sr = new System.IO.StringReader(jsonText);
            var reader = new JsonTextReader(sr);
            T result = (T) json.Deserialize(reader, typeof (T));
            reader.Close();
            return result;
        }

        #endregion

        /// <summary> 
        /// 数据表转键值对集合  
        /// 把DataTable转成 List集合, 存每一行 
        /// 集合中放的是键值对字典,存每一列 
        /// </summary> 
        /// <param name="dt">数据表</param> 
        /// <returns>哈希表数组</returns> 
        public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
        {
            var list = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                var dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }

        /// <summary> 
        /// 数据集转键值对数组字典 
        /// </summary> 
        /// <param name="ds">数据集</param> 
        /// <returns>键值对数组字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            var result = new Dictionary<string, List<Dictionary<string, object>>>();

            foreach (DataTable dt in ds.Tables)
                result.Add(dt.TableName, DataTableToList(dt));

            return result;
        }

        /// <summary> 
        /// 数据表转JSON 
        /// </summary> 
        /// <param name="dt">数据表</param> 
        /// <returns>JSON字符串</returns> 
        public static string DataTableToJson(DataTable dt)
        {
            return ObjToJson(DataTableToList(dt));
        }


        /// <summary> 
        /// 将JSON文本转换为数据表数据 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据表字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJson(string jsonText)
        {
            return JsonToObj<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
        }

        /// <summary> 
        /// 将JSON文本转换成数据行 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据行的字典</returns> 
        public static Dictionary<string, object> DataRowFromJson(string jsonText)
        {
            return JsonToObj<Dictionary<string, object>>(jsonText);
        }

        /// <summary> 
        /// 对象转JSON 
        /// </summary> 
        /// <param name="obj">对象</param> 
        /// <returns>JSON格式的字符串</returns> 
        public static string ObjectToJsonByJss(object obj)
        {
            var jss =new JavaScriptSerializer();
            try
            {
                return jss.Serialize(obj);
            }
            catch(Exception ex)
            {

                throw new Exception("JsonLib.ObjectToJson(): " + ex.Message);
            }
        }

        /// <summary> 
        /// JSON文本转对象,泛型方法 
        /// </summary> 
        /// <typeparam name="T">类型</typeparam> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>指定类型的对象</returns> 
        public static T JsonToObjectByJss<T>(string jsonText)
        {
            var jss =new JavaScriptSerializer();
            try
            {
                return jss.Deserialize<T>(jsonText);
            }
            catch(Exception ex)
            {
                throw new Exception("JsonLib.JsonToObject(): " + ex.Message);
            }
        }
    }

}
